<!--
  登录页面
-->
<template>
  <div class="login-container">
    <div class="login-card">
      <!-- Logo和标题 -->
      <div class="login-header">
        <el-icon size="48" class="logo">
          <Document />
        </el-icon>
        <h1 class="title">AI-SOES</h1>
        <p class="subtitle">智能在线考试系统</p>
      </div>

      <!-- 登录表单 -->
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        size="large"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名/邮箱"
            prefix-icon="User"
            clearable
            autocomplete="username"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
            show-password
            autocomplete="current-password"
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item>
          <div class="login-options">
            <el-checkbox v-model="loginForm.remember_me">
              记住我
            </el-checkbox>
            <el-button
              text
              type="primary"
              @click="handleForgotPassword"
            >
              忘记密码？
            </el-button>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="authStore.loading"
            @click="handleLogin"
            class="login-btn"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 其他登录方式 -->
      <div class="login-divider">
        <span>或</span>
      </div>

      <div class="other-login">
        <el-button
          size="large"
          @click="handleRegister"
          class="register-btn"
        >
          注册账号
        </el-button>
      </div>

      <!-- 快速登录账号（开发环境） -->
      <div class="quick-login" v-if="isDevelopment">
        <el-divider>
          <span class="quick-login-title">快速登录（开发环境）</span>
        </el-divider>
        <div class="quick-login-buttons">
          <el-button
            size="small"
            @click="quickLogin('admin')"
            type="danger"
          >
            管理员
          </el-button>
          <el-button
            size="small"
            @click="quickLogin('teacher')"
            type="warning"
          >
            教师
          </el-button>
          <el-button
            size="small"
            @click="quickLogin('student')"
            type="success"
          >
            学生
          </el-button>
        </div>
      </div>
    </div>

    <!-- 版权信息 -->
    <div class="copyright">
      <p>&copy; 2025 AI-SOES. All rights reserved.</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useAuthStore } from '@/stores'
import type { LoginFormData } from '@/types'
import { Document } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

const loginFormRef = ref<FormInstance>()
const isDevelopment = import.meta.env.DEV

// 登录表单数据
const loginForm = reactive<LoginFormData & { remember_me: boolean }>({
  username: '',
  password: '',
  remember_me: false
})

// 表单验证规则
const loginRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名或邮箱', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    await authStore.loginAction({
      username: loginForm.username,
      password: loginForm.password
    })

    // 登录成功后跳转
    const redirect = route.query.redirect as string
    router.push(redirect || '/dashboard')
  } catch (error) {
    console.error('Login error:', error)
  }
}

// 快速登录
const quickLogin = async (role: string) => {
  const testAccounts: Record<string, { username: string; password: string }> = {
    admin: { username: 'admin', password: 'admin123' },
    teacher: { username: 'teacher', password: 'teacher123' },
    student: { username: 'student', password: 'student123' }
  }

  const account = testAccounts[role]
  if (account) {
    loginForm.username = account.username
    loginForm.password = account.password
    await handleLogin()
  }
}

// 处理注册
const handleRegister = () => {
  router.push('/register')
}

// 处理忘记密码
const handleForgotPassword = () => {
  ElMessage.info('请联系管理员重置密码')
}

// 组件挂载时检查是否已登录
onMounted(async () => {
  await authStore.initializeAuth()
  if (authStore.isAuthenticated) {
    router.push('/dashboard')
  }
})
</script>

<style scoped lang="scss">
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;

  .login-card {
    width: 100%;
    max-width: 420px;
    background: white;
    border-radius: 16px;
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
    padding: 40px;
    margin-bottom: 20px;

    .login-header {
      text-align: center;
      margin-bottom: 40px;

      .logo {
        color: var(--el-color-primary);
        margin-bottom: 16px;
      }

      .title {
        font-size: 32px;
        font-weight: bold;
        color: var(--el-text-color-primary);
        margin: 0 0 8px 0;
      }

      .subtitle {
        font-size: 14px;
        color: var(--el-text-color-regular);
        margin: 0;
      }
    }

    .login-form {
      .login-options {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        margin-bottom: 8px;
      }

      .login-btn {
        width: 100%;
        height: 48px;
        font-size: 16px;
        font-weight: 500;
      }
    }

    .login-divider {
      text-align: center;
      margin: 24px 0;
      position: relative;

      &::before {
        content: '';
        position: absolute;
        top: 50%;
        left: 0;
        right: 0;
        height: 1px;
        background: var(--el-border-color-light);
      }

      span {
        background: white;
        padding: 0 16px;
        color: var(--el-text-color-regular);
        font-size: 14px;
      }
    }

    .other-login {
      .register-btn {
        width: 100%;
        height: 48px;
        font-size: 16px;
      }
    }

    .quick-login {
      margin-top: 24px;

      .quick-login-title {
        font-size: 12px;
        color: var(--el-text-color-placeholder);
      }

      .quick-login-buttons {
        display: flex;
        gap: 8px;
        justify-content: center;
      }
    }
  }

  .copyright {
    text-align: center;
    color: rgba(255, 255, 255, 0.8);
    font-size: 14px;

    p {
      margin: 0;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-container {
    padding: 16px;

    .login-card {
      padding: 30px 24px;

      .login-header {
        margin-bottom: 30px;

        .title {
          font-size: 28px;
        }
      }

      .login-form {
        .login-options {
          flex-direction: column;
          gap: 12px;
          align-items: flex-start;
        }
      }

      .quick-login {
        .quick-login-buttons {
          flex-direction: column;

          .el-button {
            width: 100%;
          }
        }
      }
    }
  }
}

// 暗色主题适配
[data-theme="dark"] {
  .login-container {
    background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);

    .login-card {
      background: var(--el-bg-color);
      box-shadow: 0 15px 35px rgba(0, 0, 0, 0.3);
    }
  }
}
</style>